/*
 * @Author: Superficial
 * @Date: 2021-02-22 16:51:59
 * @LastEditTime: 2021-03-03 18:19:35
 * @Description: 全局状态
 */
import { reactive, inject, readonly, ref, computed } from "vue";
import uaParser from "@/transforms/ua";

export const createGlobalState = (config) => {
  const userAgent = reactive({
    original: config.userAgent,
    language: config.language,
    ...uaParser(config.userAgent)
  })

  // 设置UA
  const setUserAgent = (_userAgent) => {
    userAgent.original = _userAgent
    Object.assign(userAgent, uaParser(config.uaParser))
  }

  // 设置语言
  const setLanguage = (_language) => {
    userAgent.language = _language
  }

  // 设置布局 侧边栏是否显示
  const isFullPage = ref(true)
  const layoutColumn = computed(() => isFullPage.value)

  const setLayoutColumn = (layoutValue) => {
    if (layoutValue !== isFullPage.value) {
      isFullPage.value = layoutValue
    }
  }

  // 客户端重置
  const resetOnClient = () => {
    setUserAgent(navigator.userAgent)
    setLanguage(navigator.language)
  }

  // 全局状态
  const globalState = {
    resetOnClient,
    layoutColumn,
    setLayoutColumn,
    userAgent: readonly(userAgent)
  }

  return {
    ...globalState,
    install(app) {
      app.provide('glboalState', globalState)
    }
  }
}

export const useGlobalState = () => {
  return inject("glboalState")
}